package cn.zy.org.service.impl;

import cn.zy.basic.service.impl.BaseServiceImpl;
import cn.zy.basic.service.impl.BaseServiceImpl;
import cn.zy.org.domain.Department;
import cn.zy.org.mapper.DepartmentMapper;
import cn.zy.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类:部门
 */
@Service
public class IDepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;


    @Override
    public List<Department> deptTree() {
        List<Department> departments = departmentMapper.loadAll();
        //1.将所有部门的信息存到map中,相当于存到内存
        //需要的时候直接根据id查找部门,不用浪费性能去查数据库,效率还低
        Map<Long,Department> map = new HashMap<>();
        for (Department department : departments) {
            map.put(department.getId(),department);
        }
        List<Department> deptTree = new ArrayList<>();
        for (Department department : departments) {
            //2.遍历所有部门,如果是顶级部门[epartment.getParent_id()==null],就加到部门树集合中
            if(department.getParent_id()==null){//顶级部门
                deptTree.add(department);
            }else{
                //3.如果不是顶级部门[department.getParent_id()!=null],
                //从map中通过getParent_id找到自己的父部门,将自己添加到children集合中
                Long id = department.getParent_id();//获取父部门的id
                Department prentDepartment = map.get(id);//获取父部门
                //防止父部门的数据删除之后引起的空指针异常
                if(prentDepartment!=null){
                    //获取父部门的children集合,将自己添加到该集合
                    prentDepartment.getChildren().add(department);
                }
            }
        }
        return deptTree;
    }
}
